package pers.lxl.structure.stack;

import java.util.Stack;

public class Solution {

    // public static void main(String[] args) {
    //     Solution solution = new Solution();
    //     System.out.println(solution.isValid("([])"));
    // }

    /**
     * 验证字符中的括号是否是一一匹配的, 例如 “([])”, 反例 “({])”
     *
     * @param s 要验证的字符串
     * @return true = 是一一匹配的. false = 不是一一匹配的
     */
    public boolean isValid(String s) {

        Stack<Character> stack = new Stack<>();

        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);

            if (c == '(' || c == '[' || c == '{') {
                stack.push(c);
            } else {
                if (stack.empty()) {
                    return false;
                }

                Character topElement = stack.pop();
                if (c == ')' && topElement != '(') {
                    return false;
                } else if (c == ']' && topElement != '[') {
                    return false;
                } else if (c == '}' && topElement != '{') {
                    return false;
                }
            }

        }

        return stack.isEmpty();
    }
}